<template>
  <div class="register-container">
    <el-card class="register-card">
      <template #header>
        <div class="card-header">
          <span>用户注册</span>
        </div>
      </template>
      <!-- 添加ref属性绑定表单引用 -->
      <el-form ref="formRef" :model="registerForm" :rules="rules" class="register-form">
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          ></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            type="email"
            placeholder="请输入邮箱"
            prefix-icon="Message"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="password2">
          <el-input
            v-model="registerForm.password2"
            type="password"
            placeholder="请再次输入密码"
            prefix-icon="Lock"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="nickname">
          <el-input
            v-model="registerForm.nickname"
            placeholder="请输入昵称"
            prefix-icon="UserFilled"
          ></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            prefix-icon="Phone"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRegister" :loading="loading" block>注册</el-button>
        </el-form-item>
        <div class="register-footer">
          <span>已有账号？</span>
          <router-link to="/login" class="login-link">立即登录</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login, register } from '../api/user'
import { setToken, setUserInfo } from '../utils/auth'

// 注册表单数据
const registerForm = ref({
  username: '',
  email: '',
  password: '',
  password2: '',
  nickname: '',
  phone: ''
})

// 表单引用
const formRef = ref(null)

// 表单验证规则
  const rules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '用户名长度在3到20个字符之间', trigger: 'blur' },
      {
        pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_\-]{3,20}$/,
        message: '用户名只能包含中文、英文、数字、下划线和连字符',
        trigger: 'blur'
      }
    ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  password2: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  nickname: [
    { max: 20, message: '昵称长度不能超过20个字符', trigger: 'blur' }
  ],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的手机号',
      trigger: 'blur'
    }
  ]
}

// 加载状态
const loading = ref(false)

// 路由实例
const router = useRouter()

// 处理注册
const handleRegister = async () => {
  try {
    // 使用ref获取表单引用进行验证
    formRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        try {
          console.log('提交注册请求:', registerForm.value)
          // 再次验证用户名编码
          const username = registerForm.value.username
          if (username) {
            // 检查是否包含无效字符
            const validUsername = /^[\u4e00-\u9fa5a-zA-Z0-9_\-]{3,20}$/.test(username)
            if (!validUsername) {
              ElMessage.error('用户名只能包含中文、英文、数字、下划线和连字符')
              loading.value = false
              return
            }
          }
          
          // 调用注册API
          console.log('准备发送注册请求，用户名:', username, '编码后:', encodeURIComponent(username))
          try {
            const response = await register(registerForm.value)
            console.log('注册响应:', response)
          } catch (error) {
            console.error('注册API错误详情:', {
              status: error.response?.status,
              data: error.response?.data,
              headers: error.response?.headers,
              request: error.request,
              message: error.message
            })
            // 显示更具体的错误信息
            if (error.response?.status === 400 && error.response?.data?.data) {
              // 提取并显示序列化器错误
              const errorDetails = error.response.data.data
              let errorMessage = '注册失败: ' 
              for (const key in errorDetails) {
                errorMessage += `${errorDetails[key].join(', ')} `
              }
              ElMessage.error(errorMessage.trim())
            } else {
              const errorMsg = error.response?.data?.message || error.message || '注册失败，请重试'
              ElMessage.error(errorMsg)
            }
            loading.value = false
            return
          }
          
          // 注册成功后自动登录
          const loginResponse = await login({
            username: registerForm.value.username,
            password: registerForm.value.password
          })
          console.log('登录响应:', loginResponse)
          
          // 尝试多种方式获取token
          let token = null
          if (loginResponse.data && loginResponse.data.tokens && loginResponse.data.tokens.access) {
            token = loginResponse.data.tokens.access
          } else if (loginResponse.data && loginResponse.data.access) {
            token = loginResponse.data.access
          } else if (loginResponse.data && loginResponse.data.token) {
            token = loginResponse.data.token
          } else if (loginResponse.access) {
            token = loginResponse.access
          } else if (loginResponse.token) {
            token = loginResponse.token
          }

          if (!token) {
            throw new Error(`登录失败: 未获取到token。响应数据: ${JSON.stringify(loginResponse)}`)
          }

          // 存储token和用户信息
          setToken(token)
          const userInfo = { 
            username: registerForm.value.username,
            email: registerForm.value.email,
            nickname: registerForm.value.nickname 
          }
          setUserInfo(userInfo)

          // 显示成功消息
          ElMessage.success('注册成功，正在跳转...')
          // 跳转到首页
          router.push('/')
        } catch (error) {
          console.error('注册或登录API错误:', error)
          const errorMsg = error.response?.data?.message || error.message || '注册失败，请重试'
          ElMessage.error(errorMsg)
        } finally {
          loading.value = false
        }
      }
    })
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage.error('注册失败，请重试')
    loading.value = false
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.register-card {
  width: 450px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
}

.register-form {
  padding: 20px;
}

.register-footer {
  text-align: center;
  margin-top: 15px;
}

.login-link {
  color: #409eff;
  cursor: pointer;
  text-decoration: none;
}

.login-link:hover {
  text-decoration: underline;
}
</style>